package com.itany.corejava.code13_jdbc;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author MissChen
 * @date 2024年03月21日 15:06
 */
public class Test03_PreparedStatement {
    public static final String JDBC_URL = "jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8";

    public static void main(String[] args) throws DataAccessException {
        List<User> users = login("cici", "123");
        System.out.println(users);
    }

    public static List<User> login(String username, String password) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(JDBC_URL, "root", "root");
            String sql = "select * from t_user where username=? and password=?";
            ps = conn.prepareStatement(sql);
            // 预编译SQL语句，为SQL语句中所有的变量赋值，每一个?表示一个变量
            // 按照顺序为每一个变量赋值，其顺序是?的顺序，起始值为1
            // 参数一：表示第几个参数
            // 参数二：实际传递的参数的值
            ps.setString(1, username);
            ps.setString(2, password);
            rs = ps.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                users.add(user);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new DataAccessException("释放连接出错");
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new DataAccessException("释放连接出错");
                }
            }
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new DataAccessException("释放连接出错");
                }
            }
        }
        return users;
    }
}
